package com.suoyue.store.controller;

import com.suoyue.store.entity.Product;

import com.suoyue.store.service.ex.ServiceException;

import com.suoyue.store.service.iLogService;
import com.suoyue.store.service.iProductService;
import com.suoyue.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("product")
public class ProductController extends BaseController{

    @Autowired
    private iProductService productService;

    @Autowired
    private iLogService logService;

    /** 头像文件大小的上限值(10MB) */
    public static final int AVATAR_MAX_SIZE = 10 * 1024 * 1024;
    /** 允许上传的头像的文件类型 */
    public static final List<String> AVATAR_TYPES = new ArrayList<String>();

    /** 初始化允许上传的头像的文件类型 */
    static {
        AVATAR_TYPES.add("image/jpeg");
        AVATAR_TYPES.add("image/png");
        AVATAR_TYPES.add("image/bmp");
        AVATAR_TYPES.add("image/gif");
    }

    @PostMapping("change_avatar")
    @ResponseBody
    public JsonResult<String> productImage(@RequestParam("file") MultipartFile file, HttpSession session) {
        // 判断上传的文件是否为空
        if (file.isEmpty()) {
            throw new ServiceException("上传的文件不允许为空");
        }
        // 判断上传的文件大小是否超出限制值
        if (file.getSize() > AVATAR_MAX_SIZE) { // getSize()：返回文件的大小，以字节为单位
            throw new ServiceException("不允许上传超过" + (AVATAR_MAX_SIZE / 1024) + "KB的文件");
        }
        // 判断上传的文件类型是否超出限制
        String contentType = file.getContentType();
        if (!AVATAR_TYPES.contains(contentType)) {
            throw new ServiceException("不支持使用该类型的文件，允许的文件类型：\n" + AVATAR_TYPES);
        }
        // 获取当前项目的绝对磁盘路径
        String parent = session.getServletContext().getRealPath("upload");
        // 保存头像文件的文件夹
        File dir = new File(parent);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 保存的头像文件的文件名
        String suffix = "";
        String originalFilename = file.getOriginalFilename();
        int beginIndex = originalFilename.lastIndexOf(".");
        if (beginIndex > 0) {
            suffix = originalFilename.substring(beginIndex);
        }
        String filename = UUID.randomUUID().toString() + suffix;

        // 创建文件对象，表示保存的头像文件
        File dest = new File(dir, filename);
        // 执行保存头像文件
        try {
            file.transferTo(dest);
        } catch (IllegalStateException e) {
            throw new ServiceException("文件状态异常，可能文件已被移动或删除");
        } catch (IOException e) {
            throw new ServiceException("上传文件时读写错误，请稍后重尝试");
        }
        // 头像路径
        String avatar = "upload/" + filename;
        System.out.println(avatar);
        // 返回成功头像路径
        return new JsonResult<String>(OK, avatar);
    }

    @RequestMapping("insertProduct")
    @ResponseBody
    public JsonResult<Product> insertProduct( String name, String description, Double price, String image) {

        System.out.println(image);
        Product data=new Product();

        data.setDescription(description);
        if("".equals(image)){
            data.setImage("item.png");
            System.out.println("image字段为空");
        }else {
            data.setImage(image);
        }
        data.setName(name);
        data.setPrice(price);

        System.out.println(data);

        productService.insert(data);

        // 将以上返回值和状态码OK封装到响应结果中并返回
        return new JsonResult<Product>(OK, data);
    }

    @RequestMapping("/detail")
    public String detail(Model model, HttpSession session, Integer pid){
        //获取pid对应的商品的数据
        Product product=productService.findProductByPid(pid);
        //添加用户的浏览记录
        logService.insertBrowseLog(getUidFromSession(session),pid);
        //将内容数据传入模板当中
        model.addAttribute("pid",pid);
        model.addAttribute("name",product.getName());
        model.addAttribute("description",product.getDescription());
        model.addAttribute("price",product.getPrice());
        model.addAttribute("image",product.getImage());
        return "detail";
    }

    @RequestMapping("getProduct")
    @ResponseBody
    public JsonResult<List<Product>> getProduct(Integer page){
        List<Product> data=productService.getProductListBypage(page);
        return new JsonResult<List<Product>>(OK, data);
    }

    @RequestMapping("getProductNum")
    @ResponseBody
    public JsonResult<Integer> getProduct(){
        Integer data=productService.getProductNum();
        return new JsonResult<Integer>(OK, data);
    }

    @RequestMapping("updateProduct")
    @ResponseBody
    public JsonResult<Integer> updateProduct(Integer pid,String name,String description,Double price,String image){
        Integer data=productService.updateProductByPid(pid, name, description, price, image);
        return new JsonResult<Integer>(OK, data);
    }

    @RequestMapping("deleteProduct")
    @ResponseBody
    public JsonResult<Integer> deleteProduct(Integer pid){
        Integer data=productService.deleteProduct(pid);
        return new JsonResult<Integer>(OK, data);
    }


    @RequestMapping("getProductDetail")
    @ResponseBody
    public JsonResult<Product> getProductDetail(Integer pid){
        Product data=productService.findProductByPid(pid);
        return new JsonResult<Product>(OK, data);
    }


}
